﻿using CPPEI.Coolzon.Common;
using CPPEI.Coolzon.Configuration.Client;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;

namespace CPPEI.Coolzon.Designer.Shell
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        protected override void OnStartup(StartupEventArgs e)
        {
            System.Windows.Application.Current.DispatcherUnhandledException += App_DispatcherUnhandledException;
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            System.Windows.Application.Current.ShutdownMode = ShutdownMode.OnMainWindowClose;

            Logger.InitByLogDirectory(CZEnvironment.GetLogDirectory());
            Logger.Debug("程序启动!");

            CPPEI.Coolzon.Configuration.Client.Config.InitHostConfig(CZEnvironment.GetHostConfigFilePath());
            CPPEI.Coolzon.Configuration.Client.Config.InitPartLibsConfig(CZEnvironment.GetPartLibConfigFilePath());
            Config.PartLibs.PartLibsBaseAddress = CZEnvironment.GetPartLibBaseAddress();

            // 初始化属性的转换器和编辑器配置信息
            CPPEI.Coolzon.UI.XProperty.PropertyValueConverterFactory.Init(string.Format("{0}\\Config\\XProperty.xml",
                AppDomain.CurrentDomain.BaseDirectory));

            // 初始化资源池对象
            CPPEI.Coolzon.Designtime.ResPoolFactory.Init(string.Format("{0}\\Config\\XResPool.xml",
                AppDomain.CurrentDomain.BaseDirectory));

            // 初始化DesignTime.Metadata.Storage
            Designtime.Metadata.Storage.InitWithDirectory(string.Format("C:\\Coolzon\\Designer\\V{0}\\DesigntimeStorage\\", CZEnvironment.Version4));

            base.OnStartup(e);
        }
        void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            try
            {
                if (e.ExceptionObject is Exception)
                {
                    Common.Logger.ErrorToTag(this.GetType().ToString(), ((Exception)e.ExceptionObject).Message);
                }
            }
            catch (Exception ex)
            {
                Common.Logger.ErrorToTag(this.GetType().ToString(), ex.Message);
            }
        }

        void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            try
            {
                Common.Logger.ErrorToTag(this.GetType().ToString(), e.Exception.Message);
                e.Handled = true;
            }
            catch (Exception ex)
            {
                Common.Logger.ErrorToTag(this.GetType().ToString(), ex.Message);
            }

        }
    }
}
